package com.jh.user.service;

import cn.jh.common.pojo.BaseResponse;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.TokenUtil;
import com.jh.user.business.ShopRegisterBussiness;
import com.jh.user.business.TerminalInfoBussiness;
import com.jh.user.pojo.Platform;
import com.jh.user.pojo.ShopRegister;
import com.jh.user.pojo.TerminalInfo;
import com.jh.user.util.CommonsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@EnableAutoConfiguration
@Controller
public class TerminalInfoService {

    @Autowired
    private TerminalInfoBussiness terminalInfoBussiness;
    @Autowired
    private ShopRegisterBussiness shopRegisterBussiness;
    @Autowired
    private PlatformService platformService;

    private Logger log = LoggerFactory.getLogger(TerminalInfoService.class);

    /**
     * 分页查询
     *
     * @param request
     * @param shopId
     * @param shopName
     * @param terminalType
     * @param terminalNo
     * @param machineNo
     * @param evmNo
     * @param startTime
     * @param endTime
     * @param page
     * @param size
     * @param direction
     * @param sortProperty
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/user/terminalInfo/find")
    public @ResponseBody
    Object findPage(
            HttpServletRequest request,
            @RequestParam(value = "shopId", defaultValue = "", required = false) String shopId,
            @RequestParam(value = "shopName", defaultValue = "", required = false) String shopName,
            @RequestParam(value = "terminalType", required = false) Integer terminalType,
            @RequestParam(value = "terminalNo", defaultValue = "", required = false) String terminalNo,
            @RequestParam(value = "machineNo", defaultValue = "", required = false) String machineNo,
            @RequestParam(value = "evmNo", defaultValue = "", required = false) String evmNo,
            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
        return BaseResponse.success(terminalInfoBussiness.findByShopIdAndShopNameAndTerminalTypeAndTerminalNo(shopId, shopName, terminalType, terminalNo, machineNo, evmNo, startTime, endTime, pageable));
    }


    /**
     * 增加终端
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/terminal/add/{token}")
    public @ResponseBody
    Object addTerminalRegister(HttpServletRequest request,
                               TerminalInfo terminalInfo,
                               @PathVariable("token") String token) {
        //校验参数0pos  1台卡
        if ("0".equals(terminalInfo.getTerminalType())) {
            //pos参数校验

            if (!terminalInfo.equalsPos(terminalInfo)) {
                return BaseResponse.error(CommonConstants.FALIED, "参数校验失败");
            }
        } else if ("1".equals(terminalInfo.getTerminalType())) {
            //台卡参数校验
            if (!terminalInfo.equalsTaiKa(terminalInfo)) {
                return BaseResponse.error(CommonConstants.FALIED, "参数校验失败");
            }
        } else {
            return BaseResponse.error(CommonConstants.FALIED, "终端类型暂不支持");
        }

        try {
            Long userId = TokenUtil.getUserId(token);
            if (userId == null) {
                return BaseResponse.error(CommonConstants.ERROR_USER_NOT_EXISTED, "用户未登录");
            }
            terminalInfo.setUserId(userId);
            terminalInfoBussiness.mergeTerminalInfo(terminalInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.error("添加失败，请稍后再试");

        }

        return BaseResponse.success();
    }

    /**
     * 修改终端pos
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/terminal/update/pos/{token}")
    public @ResponseBody
    Object updateTerminalpos(HttpServletRequest request,
                             TerminalInfo terminalInfo,
                             @PathVariable("token") String token) {
        if (!"0".equals(terminalInfo.getTerminalType())) {
            return BaseResponse.error(CommonConstants.FALIED, "终端类型暂不支持");
        }
        try {
            Long userId = TokenUtil.getUserId(token);
            if (userId == null) {
                return BaseResponse.error(CommonConstants.ERROR_USER_NOT_EXISTED, "用户未登录");
            }
            terminalInfo.setUserId(userId);
            terminalInfoBussiness.updateTerminalPos(terminalInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.error("修改失败，请稍后再试");

        }

        return BaseResponse.success();
    }

    /**
     * 修改终端台卡
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/terminal/update/tk/{token}")
    public @ResponseBody
    Object updateTerminalTk(HttpServletRequest request,
                            TerminalInfo terminalInfo,
                            @PathVariable("token") String token) {
        if (!"1".equals(terminalInfo.getTerminalType())) {
            return BaseResponse.error(CommonConstants.FALIED, "终端类型暂不支持");
        }
        try {
            Long userId = TokenUtil.getUserId(token);
            if (userId == null) {
                return BaseResponse.error(CommonConstants.ERROR_USER_NOT_EXISTED, "用户未登录");
            }
            terminalInfo.setUserId(userId);
            terminalInfoBussiness.updateTerminalTk(terminalInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.error("修改失败，请稍后再试");

        }

        return BaseResponse.success();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/terminal/find/shopId")
    public @ResponseBody
    Object findTerminalByShopId(HttpServletRequest request,
                                @RequestParam("shopId") String shopId
    ) {

        return BaseResponse.success(terminalInfoBussiness.findByShopId(shopId));
    }

    /**
     * 删除終端
     */
    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/user/store/delete/terminal/{token}")
    public @ResponseBody
    Object deleteTerminalInfo(HttpServletRequest request, @RequestParam("shopId") String shopId, @RequestParam("terminalNo") String terminalNo,
                              @PathVariable("token")String token) throws Exception {
        try {
            Long userId = TokenUtil.getUserId(token);
            if (userId == null) {
                return BaseResponse.error(CommonConstants.ERROR_USER_NOT_EXISTED, "用户未登录");
            }
            terminalInfoBussiness.deleteTerminalInfo(shopId,terminalNo);

        } catch (Exception e) {
            log.error("TerminalInfoService.deleteTerminalInfo, 删除終端异常=" + e);
            return CommonsUtil.returnError("删除終端失败！");
        }
        return BaseResponse.success();
    }


    //生成二维码
/*
    @RequestMapping(method = RequestMethod.POST,value = "/v1.0/user/add/evmImg/{token}")
    public  @ResponseBody ObjectaddEvmImg(HttpServletRequest request,@RequestParam("shopId"))*/

    /**
     * 根据shop_id查询台码列表
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/queryPlatFrom/{token}")
    public @ResponseBody Object queryPlatFromByShopId(
            @RequestParam("shop_id") String shopId,
            @PathVariable("token")String token,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
        log.info("根据shop_id查询台码列表shopId = " + shopId);
        Long userId = 0l;
        try {
            userId = TokenUtil.getUserId(token);
            if (null == userId) {
                return CommonsUtil.returnError("用户为登陆");
            }

            if (StringUtils.isEmpty(shopId)) {
                return CommonsUtil.returnError("shop_id为空");
            }

            ShopRegister shopRegister = shopRegisterBussiness.findByShopId(shopId);
            log.info("shopId = " + shopId + "获取商户注册信息shopRegister：" + shopRegister.toString());
            if (null == shopRegister) {
                return CommonsUtil.returnError("获取商户注册信息失败");
            }

            String mobilePhone = null == shopRegister.getMobilePhone() ? "" : shopRegister.getMobilePhone();
            if (StringUtils.isEmpty(mobilePhone)) {
                return CommonsUtil.returnError("获取商户手机号失败");
            }

            Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
            Page<Platform> platforms = platformService.queryPlatFromByShopId(mobilePhone, pageable);
            return CommonsUtil.returnSuccess(platforms);
        } catch (Exception e) {
            log.error("userId = " + userId + "TerminalInfoService.queryPlatFromByShopId根据shop_id查询台码列表异常");
            return CommonsUtil.returnError("系统异常，请售后再试！");
        }
    }
}